package cn.edu.hit.core.message;

import com.fasterxml.jackson.databind.ObjectMapper;
import cn.edu.hit.core.Document;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Logger;
import java.util.stream.Stream;

public abstract class MessageAdapterHelper2<T> implements MessageAdapter {
    protected static final Logger logger = Logger.getLogger("MessageAdapter");
    protected static final ObjectMapper mapper = new ObjectMapper();

    protected ConcurrentMap<String, Map> configureMap = new ConcurrentHashMap<>();

    @Override
    public final void register(String id, Map config) {
        configureMap.put(id, config);
    }

    @Override
    public final void clear() {
        configureMap.clear();
    }

    @Override
    public final Stream<Map> service(Long timestamp) {
        prepose(timestamp);
        T t = pretreat(timestamp);
        return configureMap.entrySet().parallelStream().map(entry -> {
            Document result = new Document();
            String id = entry.getKey();
            Document configure = (Document) entry.getValue();

            result.put(PORT_ID, id);
            result.put("portName", configure.getString("portName"));

            result.put(VALUE, getValue(t, id, configure));

            result.put(TIMESTAMP, timestamp);
            return result;
        });
    }

    /**
     * 根据测点id 从中间计算结果中取值
     *
     * @param t         中间计算结果
     * @param id        测点id
     * @param configure
     * @return 测点的最终值
     */
    protected abstract Object getValue(T t, String id, Document configure);

    /**
     * 中间计算
     *
     * @param timestamp
     * @return
     */
    protected T pretreat(Long timestamp) {
        return null;
    }

    /**
     * 前置操作
     *
     * @param timestamp
     */
    protected void prepose(Long timestamp) {

    }

    ;
}
